package org.duang.render;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.duang.config.Config;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;



public class JsonRender extends Render {

	private static final long serialVersionUID = -6757577835886443202L;
	private static Logger logger = LoggerFactory.getLogger(JsonRender.class);
	private static final String contentType = "application/json;charset=" + Config.getEncoding();
//	private static final String defaultContentType = "text/plain;charset=" + Config.ENCODING;
	
	private Set<String> fieldFilterSet ;  
	
	public class CustomFieldPropertyFilter implements PropertyFilter {  
			private Set<String> filterSet = new HashSet<String>();
			//@Override  
		    public boolean apply(Object source, String name, Object value) {  
	            for(Iterator<String> it =  filterSet.iterator(); it.hasNext();){
//	            	System.out.println(source.getClass().getName()); // TODO 可以通过反射，取得对应的类字段，再组装成key与name比较
	                if(it.next().equals(name)){  
	                    return false;  
	                }  
	            }
		        return true;  
		    }  
		      
		    public CustomFieldPropertyFilter(Set<String> filterSet){  
		        this.filterSet = filterSet;  
		    }  
		}  
	
	public static Render init(){
		return new JsonRender(null);
	}
	
	public JsonRender(Object obj){
		this.obj = obj;
	}
	
	public JsonRender(Object obj, Set<String> fieldFilterSet){
		this.obj = obj;
		this.fieldFilterSet = fieldFilterSet;
	}
	
	
	
	@Override
	public void render() {
		PrintWriter writer = null;
		try {
			response.setHeader("Pragma", "no-cache");	
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType(contentType);
			response.setCharacterEncoding(Config.getEncoding());
			writer = response.getWriter();
//			logger.debug("returnJSON: " + JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
//	        writer.write(JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
			if(ToolsKit.isNotEmpty(fieldFilterSet)){				  
				  CustomFieldPropertyFilter customFieldPropertyFilter = new CustomFieldPropertyFilter(fieldFilterSet);
				  SerializeWriter serializeWriter = new SerializeWriter();
				  JSONSerializer serializer = new JSONSerializer(serializeWriter);
				  serializer.setDateFormat("yyyy-MM-dd HH:mm:ss");
				  serializer.getPropertyFilters().add(customFieldPropertyFilter);	
				  //https://github.com/alibaba/fastjson/wiki/Class_Level_SerializeFilter
//				  SerializeConfig.getGlobalInstance().addFilter(A.class, customFieldPropertyFilter);c
				  serializer.write(obj);
				  writer.write(serializeWriter.toString());
				  fieldFilterSet.clear();
			} else {
				writer.write(ToolsKit.toJsonString(obj));
			}
			writer.flush();
		} catch (Exception e) {
			logger.debug("returnJson exception:  "+e.getMessage(), e);
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
		finally {
			if (writer != null){
				writer.close();
			}
		}
	}
}
